import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import Layout from '@/views/Layout.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { title: '注册', requiresAuth: false }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/hosts',
    meta: { requiresAuth: true },
    children: [
      {
        path: '/hosts',
        name: 'Hosts',
        component: () => import('@/views/Hosts.vue'),
        meta: { title: '主机管理', requiresAuth: true }
      },
      {
        path: '/host-groups',
        name: 'HostGroups',
        component: () => import('@/views/HostGroups.vue'),
        meta: { title: '主机组管理', requiresAuth: true }
      },
      {
        path: '/projects',
        name: 'Projects',
        component: () => import('@/views/Projects.vue'),
        meta: { title: '项目管理', requiresAuth: true }
      },
      {
        path: '/environments',
        name: 'Environments',
        component: () => import('@/views/Environments.vue'),
        meta: { title: '环境管理', requiresAuth: true }
      },
      {
        path: '/users',
        name: 'Users',
        component: () => import('@/views/Users.vue'),
        meta: { title: '用户管理', requiresAuth: true }
      },
      {
        path: '/user-groups',
        name: 'UserGroups',
        component: () => import('@/views/UserGroups.vue'),
        meta: { title: '用户组管理', requiresAuth: true }
      },
      {
        path: '/terminal/:id',
        name: 'Terminal',
        component: () => import('@/views/Terminal.vue'),
        meta: { title: 'SSH终端', requiresAuth: true }
      },
      {
        path: '/profile',
        name: 'UserProfile',
        component: () => import('@/views/UserProfile.vue'),
        meta: { title: '个人资料', requiresAuth: true }
      },
      {
        path: '/inspection',
        name: 'Inspection',
        component: () => import('@/views/Inspection.vue'),
        meta: { title: '系统巡检', requiresAuth: true }
      },
      {
        path: '/recipients',
        name: 'Recipients',
        component: () => import('@/views/Recipients.vue'),
        meta: { title: '收件人管理', requiresAuth: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('access_token')
  
  // 需要登录的页面
  if (to.meta.requiresAuth) {
    if (!token) {
      ElMessage.warning('请先登录')
      next('/login')
    } else {
      next()
    }
  } else {
    // 已登录用户访问登录页，跳转到首页
    if ((to.path === '/login' || to.path === '/register') && token) {
      next('/')
    } else {
      next()
    }
  }
})

export default router
